package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"shopping/model/mysql"
	"shopping/model/redis"
	"strconv"
	"time"

	"shopping/shoppingrpc/internal/svc"
	"shopping/shoppingrpc/shoppingrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ShopListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewShopListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShopListLogic {
	return &ShopListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ShopListLogic) ShopList(in *shoppingrpc.ShopListRequest) (*shoppingrpc.ShopListResponse, error) {
	// todo: add your logic here and delete this line
	page := in.Page
	if page <= 0 {
		page = 1
	}
	size := in.Size
	switch {
	case size > 100:
		size = 100
	case size <= 0:
		size = 10
	}
	offset := (page - 1) * size
	var shop []mysql.Products
	itoa := strconv.Itoa(int(offset))
	get := redis.Client.Get("shopList" + itoa)
	if get.Val() == "" {
		mysql.DB.Debug().Offset(int(offset)).Limit(int(size)).Where("name like ?", "%s"+in.Name+"%").Order("price desc").Find(&shop)
		marshal, _ := json.Marshal(&shop)
		redis.Client.Set("shopList"+itoa, marshal, time.Hour*24)
		fmt.Println("mysql")
	} else {
		json.Unmarshal([]byte(get.Val()), &shop)
		fmt.Println("rides")
	}
	var shopList []*shoppingrpc.ShopList
	for _, m := range shop {
		list := shoppingrpc.ShopList{
			Image:      m.Image,
			Name:       m.Name,
			Navigation: m.Navigation,
			Label:      m.Label,
			Price:      float32(m.Price),
			Money:      float32(m.Money),
			Stock:      int64(m.Stock),
			Sales:      int64(m.Sales),
			Status:     m.Status,
		}
		shopList = append(shopList, &list)
	}
	return &shoppingrpc.ShopListResponse{List: shopList}, nil
}
